const db  = require('../db/index')
// 导入加密包
const bcrypt = require('bcryptjs')

exports.getuserinfo = (req, res)=>{
    const sql = 'select id, username, email,user_pic from ev_users where id = ?'
    db.query(sql,req.user.id,(err, result)=>{
        if(err) return res.cc(err)
        if(result.length !== 1) return res.cc('获取用户信息失败！')
        res.send({
            status: 0, 
            message: '获取用户信息成功！',
            data: result[0]
        })
    })
}

exports.updateuserinfo = (req,res)=>{
    const sql = 'update ev_users set ? where id = ?'
    db.query(sql,[req.body,req.user.id],(err, result)=>{
        if(err) return res.cc(err)
        if(result.affectedRows !== 1) return res.cc('更改用户信息失败！'+result[0])
        res.cc('更改用户信息成功！')
    })
}

exports.updatepassword = (req, res)=>{
    const sql = 'select * from ev_users where id = ?'
    db.query(sql,req.user.id,(err, result)=>{
        if(err) return res.cc(err)
        if(result.length !== 1) return res.cc('用户不存在！')

        const compare = bcrypt.compareSync(req.body.oldPwd,result[0].password)
        if(!compare) return res.cc('旧密码错误！')

        const sql = 'update ev_users set password=? where id = ?'
        const newPwd = bcrypt.hashSync(req.body.newPwd,10)
        db.query(sql,[newPwd,req.user.id],(err, result)=>{
            if(err) return res.cc(err)
            if(result.affectedRows !== 1) return res.cc('更改密码失败！'+result[0])
            res.cc('更改密码成功！')
        })
    })
}

exports.update_avatar = (req, res)=>{
    const sql = 'update ev_users set user_pic=? where id = ?'
    db.query(sql,[req.body.avatar,req.user.id],(err, result)=>{
        if(err) return res.cc(err)
        if(result.affectedRows !== 1) return res.cc('更改头像失败！'+result[0])
        res.cc('更改头像成功！')
    })
}